import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import Item from '../Item/Item'
import './List.css'

export default class List extends Component {

    state = {
        userList: [],
        isFirst: true, // 是否为第一次打开页面
        isLoading: false, // 标识是否处于加载中
        isError: '', // 请求错误信息
    }

    componentDidMount() {
        this.searchToken = PubSub.subscribe('search', (_, data) => {
            this.setState(data)
        })
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this.searchToken)
    }

    render() {
        const { userList, isFirst, isLoading, isError } = this.state
        return (
            <div className="list">
                {
                    isFirst ? <h3>Welcome to The Github Search Tools</h3> :
                        isLoading ? <h3>loading...</h3> :
                            isError ? <h3>{isError}</h3> :
                                userList.map(v => {
                                    return <Item key={v.id} {...v} />
                                })
                }
            </div>
        )
    }
}
